package com.woniuxy.springparking.controller;

import com.woniuxy.springparking.asepct.SysLog;
import com.woniuxy.springparking.common.RestDto;
import com.woniuxy.springparking.common.RestResult;
import com.woniuxy.springparking.pojo.User;
import com.woniuxy.springparking.service.UserService;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;


@RestController
public class LoginController {
    @Autowired
    private UserService userService;

    @PostMapping(value = "/login.do")
    @ApiOperation(value = "登陆",httpMethod = "POST",
            protocols = "HTTP",produces = "application/json",
            response = RestDto.class,notes = "登陆")
    @SysLog(value1 = "登录",value2 = "")
    public RestDto login(String telephone,
                            String password,
//                            @RequestParam(value = "isRememberMe",defaultValue = "0") Integer isRememberMe,
                            HttpServletRequest request){
        System.out.println(telephone+password);
        Subject subject=SecurityUtils.getSubject();
        UsernamePasswordToken token=new UsernamePasswordToken(telephone,password);
        /*
        if(isRememberMe==1){
            token.setRememberMe(true);//如果设置参数为true，表示实现记住我的功能
        }*/
        try {
            subject.login(token);
            User user=this.userService.findUserByUserName(telephone);
            //获取Session对象
            Session session=subject.getSession();
            session.setAttribute("USER_SESSION",user);
            return new RestDto(200,"登录成功");
        } catch (AuthenticationException e) {
            e.printStackTrace();
            request.setAttribute("error","用户名或者密码有误");
            return new RestDto(1001,"用户名或密码不正确");
        }
    }

}
